package com.logos.musicframe.task;

import com.alibaba.fastjson.JSON;
import com.formdev.flatlaf.json.Json;
import com.logos.musicframe.constant.RedisConstant;
import com.logos.musicframe.entity.Songs;
import com.logos.musicframe.mapper.SongsMapper;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.service.SongsService;
import com.logos.musicframe.utils.RedisUtil;
import com.logos.musicframe.utils.UserInfoUtil;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author logos
 * date 2025/6/9 13:10
 * @version v1.0
 * @Package com.logos.musicframe.task
 */
@Component
@Slf4j
public class SongTask {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SongsService songsService;

    @Autowired
    private UserInfoUtil userInfoUtil;
    
    // 添加锁，防止并发调用时的问题
    private final ReentrantLock lock = new ReentrantLock();

    // 每10秒执行一次
    @Scheduled(cron = "0/10 * * * * ?")
    // 每分钟执行一次
//    @Scheduled(cron = "0 0/1 * * * ?")
    public void dayRandomSong(){
        refreshRecommendSongs();
    }
    
    /**
     * 刷新推荐歌曲
     * 该方法可以被定时任务调用，也可以在用户登录后手动调用
     * @return 是否刷新成功
     */
    public boolean refreshRecommendSongs() {
        try {
            // 获取锁，防止并发问题
            lock.lock();
            
            // 从全部歌曲中抽取三首
            List<SongsResp> songsRespList = new ArrayList<>();
            if (!redisUtil.exist(RedisConstant.ALL_SONG)){
                songsRespList = songsService.queryAll(userInfoUtil.getUserId());
                // 存入redis
                redisUtil.setNx(RedisConstant.ALL_SONG, JSON.toJSONString(songsRespList),RedisConstant.EXPIRE_TIME_THREE_MINUTES);
            }else{
                String allSongStr = redisUtil.get(RedisConstant.ALL_SONG);
                // 转换为list
                songsRespList = JSON.parseArray(allSongStr, SongsResp.class);
            }
            
            // 如果没有歌曲，返回失败
            if (songsRespList == null || songsRespList.isEmpty()) {
                log.warn("SongTask:refreshRecommendSongs: 没有可用的歌曲");
                return false;
            }
            
            // 打乱顺序
            Collections.shuffle(songsRespList);
            
            // 确定要选择的歌曲数量（最多3首，如果总数不足则全部选择）
            int selectCount = Math.min(3, songsRespList.size());
            List<SongsResp> selectedSongs = songsRespList.subList(0, selectCount);
            
            log.info("SongTask:refreshRecommendSongs:selectedSongs:{}", selectedSongs);
            
            // 随机抽取三首存入缓存中 key:songs:day:2025-06-09
            String key = RedisConstant.SONGS_DAY+ LocalDate.now();
            redisUtil.del(key);
            redisUtil.setNx(key, JSON.toJSONString(selectedSongs), RedisConstant.EXPIRE_TIME_ONE_DAY);
            
            return true;
        } catch (Exception e) {
            log.error("SongTask:refreshRecommendSongs: 刷新推荐歌曲失败", e);
            return false;
        } finally {
            lock.unlock();
        }
    }
}
